package com.open.source.kafka;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

/**
 * @description: ApplicationContextHolder
 * @author: wangweir
 * @date: 2019/6/27 19:40
 */
@Component
public class ApplicationContextHolder implements ApplicationContextAware {

  private static ApplicationContext applicationContext = null;

  @Override
  public void setApplicationContext(@NonNull ApplicationContext applicationContext)
      throws BeansException {
    if (ApplicationContextHolder.applicationContext == null) {
      ApplicationContextHolder.applicationContext = applicationContext;
    }
  }

  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }

  public static Environment getEnvironment() {
    return applicationContext.getEnvironment();
  }

  public static Object getBean(String name) {
    return getApplicationContext().getBean(name);
  }

  public static String getProperty(String key) {
    return getEnvironment().getProperty(key);
  }

  public static String getProperty(String key, String defaultVal) {
    return getEnvironment().getProperty(key, defaultVal);
  }

  public static <T> T getBean(Class<T> clazz) {
    return getApplicationContext().getBean(clazz);
  }

  public static <T> T getBean(String name, Class<T> clazz) {
    return getApplicationContext().getBean(name, clazz);
  }

  public static <T> String[] getBeanNamesForType(Class<T> clazz) {
    return getApplicationContext().getBeanNamesForType(clazz);
  }

  public static <T> List<T> getBeansForType(Class<T> clazz) {
    final List<T> beans = new ArrayList<>();
    final String[] beanNamesForType = getBeanNamesForType(clazz);
    for (String beanName : beanNamesForType) {
      final T bean = getApplicationContext().getBean(beanName, clazz);
      beans.add(bean);
    }
    return beans;
  }

}
